package com.fy.oa.zc.crm;

import java.text.SimpleDateFormat;
//import java.io.BufferedReader;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.io.OutputStream;
//import java.net.HttpURLConnection;
//import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.Map;


//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.fy.oa.zc.domain.FySummaryView;
import com.fy.oa.zc.exception.FyOAException;
import com.fy.oa.zc.manager.AFyOA_FormEventManager;
import com.fy.oa.zc.manager.FyOA_FormEventManager;
import com.fy.oa.zc.soap.client.FyOA_SOAPClient;

public final class FyOA2CRM_QuotationCovers_ManagerImpl extends AFyOA_FormEventManager implements FyOA_FormEventManager {
	private String soapServicePath="http://10.111.0.162:7777";
	
	public void setSoapServicePath(String soapServicePath) {
		this.soapServicePath = soapServicePath;
	}
	public String toString() {
		return "定价审批";
	}
	
	private void resultParse(String xml) {
		try {
			Document doc = DocumentHelper.parseText(xml);
			doc.getRootElement().addNamespace("siebelf","http://www.siebel.com/ws/fault");
			doc.getRootElement().addNamespace("ns","http://siebel.com/CustomUI");
			List<?> list = doc.selectNodes("//ns:ErrorMessage");
			if (list.size() == 1) {
				Element node = (Element) list.get(0);
				String msg = node.getText();
				if (msg != null && !"".equals(msg)) {
					throw new FyOAException("新客户授信审批信息写入CRM失败，错误提示为：" + msg);
				}
			} else if (list.size() == 0) {
				list = doc.selectNodes("//siebelf:errormsg");
				if (list.size() == 1) {
					throw new FyOAException("新客户授信审批信息写入CRM失败，错误提示为：" + ((Element) list.get(0)).getText());
				}
				throw new FyOAException("新客户授信审批信息写入CRM失败，未知的错误！");
			} else {
				throw new FyOAException("新客户授信接口返回XML数据异常，出现多个ErrorMessage");
			}
		} catch (DocumentException e) {
			throw new FyOAException("解析新客户授信接口返回XML数据发生异常", e);
		}
	}

	@Override
	public String dealProcessEvent(FySummaryView view, long affairid) {
		NewCustomer newCustomer = getQuotationCoversByAffairID(view.getSummaryid(), affairid);
		newCustomer.setAccountfinalstatus("");
		resultParse(send(newCustomer));
		return view.toString();
	}

	@Override
	public String dealFinishEvent(FySummaryView view, long affairid) {
		NewCustomer newCustomer = getQuotationCoversByAffairID(view.getSummaryid(), affairid);
		newCustomer.setAccountfinalstatus("生效");
		resultParse(send(newCustomer));
		return view.toString();
	}

	@Override
	public String dealStopEvent(FySummaryView view) {
		NewCustomer newCustomer = getQuotationCovers_STOP(view.getSummaryid());
		newCustomer.setAccountfinalstatus("拒绝");
		resultParse(send(newCustomer));
		return view.toString();
	}

	@Override
	public String dealCancelEvent(FySummaryView view, long userid, String message) {
		NewCustomer newCustomer = getQuotationCovers_Cancel(view.getSummaryid(), userid, message);
		newCustomer.setAccountfinalstatus("拒绝");
		resultParse(send(newCustomer));
		return view.toString();
	}

	@Override
	public String dealStepBackEvent(FySummaryView view) {
		NewCustomer newCustomer = getQuotationCovers_StepBack(view.getSummaryid());
		newCustomer.setAccountfinalstatus("");
		resultParse(send(newCustomer));
		return view.toString();
	}

	private String send(NewCustomer newCustomer) {
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(XMLTEMPLATE);
		} catch (DocumentException e) {
			throw new FyOAException("解析XML模板失败", e);
		}
		((org.dom4j.Element) doc.selectNodes("//cus:FYOAApproveServiceAccntApprove_Input//cus:Accountfinalstatus")
				.get(0)).setText(newCustomer.getAccountfinalstatus());
		((org.dom4j.Element) doc.selectNodes("//cus:FYOAApproveServiceAccntApprove_Input//cus:AccounId").get(0))
				.setText(newCustomer.getAccounId());
		((org.dom4j.Element) doc.selectNodes("//cus:FYOAApproveServiceAccntApprove_Input//cus:Accountmessage").get(0))
				.setText(newCustomer.getAccountmessage());
		((org.dom4j.Element) doc.selectNodes("//cus:FYOAApproveServiceAccntApprove_Input//cus:Accountposition").get(0))
				.setText(newCustomer.getAccountposition());
		((org.dom4j.Element) doc.selectNodes("//cus:FYOAApproveServiceAccntApprove_Input//cus:Oacreateddatetime")
				.get(0)).setText(newCustomer.getAacreateddatetime());
		return fyOA_SOAPClient.post(doc.asXML(),
				soapServicePath + "/eai_anon_chs/start.swe?SWEExtSource=SecureWebService&SWEExtCmd=Execute",
				"\"document/http://siebel.com/CustomUI:FYOAApproveServiceAccntApprove\"");
	}

	private NewCustomer getQuotationCoversByAffairID(long summaryid, long affairid) {
		NewCustomer newCustomer = null;
		String quotationCoversID = getValues(summaryid).get("报价履历Id");
		Map<String, Object> temp = jdbcTemplate.queryForMap(QUERYMESSAGE_PROCESS_SQL, new Object[] { affairid });
		if (temp != null) {
			newCustomer = new NewCustomer();
			newCustomer.setAccounId(quotationCoversID);
			newCustomer.setAacreateddatetime(getNowTime());
			newCustomer.setAccountposition((String) temp.get("member"));
			newCustomer.setAccountmessage(
					new StringBuilder().append("【").append(fyOAConf.getDelAttitude((String) temp.get("opinion")))
							.append("】    ").append((String) temp.get("msg")).toString());
		}
		return newCustomer;
	}

	private NewCustomer getQuotationCovers_STOP(long summaryid) {
		NewCustomer newCustomer = null;
		String quotationCoversID = getValues(summaryid).get("客户Id");
		Map<String, Object> temp = jdbcTemplate.queryForMap(QUERYMESSAGE_STOP_SQL, new Object[] { summaryid });
		if (temp != null) {
			newCustomer = new NewCustomer();
			newCustomer.setAccounId(quotationCoversID);
			newCustomer.setAacreateddatetime(getNowTime());
			newCustomer.setAccountposition((String) temp.get("member"));
			newCustomer.setAccountmessage(
					new StringBuilder().append("【").append(fyOAConf.getDelAttitude((String) temp.get("opinion")))
							.append("】    ").append((String) temp.get("msg")).toString());
		}
		return newCustomer;
	}

	private NewCustomer getQuotationCovers_Cancel(long summaryid, long userID, String msg) {
		NewCustomer newCustomer = null;
		String quotationCoversID = getValues(summaryid).get("客户Id");
		String temp = jdbcTemplate.queryForObject(QUERYMESSAGE_CANCEL_SQL, new Object[] { userID }, String.class);
		if (temp != null) {
			newCustomer = new NewCustomer();
			newCustomer.setAccounId(quotationCoversID);
			newCustomer.setAacreateddatetime(getNowTime());
			newCustomer.setAccountposition(temp);
			newCustomer.setAccountmessage(new StringBuilder().append("【撤销】    ").append(msg).toString());
		}
		return newCustomer;
	}

	private NewCustomer getQuotationCovers_StepBack(long summaryid) {
		NewCustomer newCustomer = null;
		String quotationCoversID = getValues(summaryid).get("客户Id");
		Map<String, Object> temp = jdbcTemplate.queryForMap(QUERYMESSAGE_STEPBACK_SQL, new Object[] { summaryid });
		if (temp != null) {
			newCustomer = new NewCustomer();
			newCustomer.setAccounId(quotationCoversID);
			newCustomer.setAacreateddatetime(getNowTime());
			newCustomer.setAccountposition((String) temp.get("member"));
			newCustomer.setAccountmessage(
					new StringBuilder().append("【").append(fyOAConf.getDelAttitude((String) temp.get("opinion")))
							.append("】    ").append((String) temp.get("msg")).toString());
		}
		return newCustomer;
	}
	
	public String getNowTime(){
		java.util.Date date= Calendar.getInstance().getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		return sdf.format(date);
	}

	public void setFyOA_SOAPClient(FyOA_SOAPClient fyOA_SOAPClient) {
		this.fyOA_SOAPClient = fyOA_SOAPClient;
	}

	private FyOA_SOAPClient fyOA_SOAPClient;

	private static final String QUERYMESSAGE_PROCESS_SQL = "select to_char(a.CONTENT) msg,p.NAME||'/'||m.name member,a.EXT_ATT1 opinion\n"
			+ "from CTP_COMMENT_ALL a left join ORG_MEMBER m on a.CREATE_ID = m.id \n"
			+ "left join ORG_POST p on m.ORG_POST_ID = p.id\n"
			+ "where (a.AFFAIR_ID,a.CREATE_DATE) in ( select a1.affair_id,max(a1.create_date) from CTP_COMMENT_ALL a1 where a1.AFFAIR_ID=? group by a1.affair_id)  and rownum = 1";

	private static final String QUERYMESSAGE_STOP_SQL = "select to_char(a.CONTENT) msg,p.NAME||'/'||m.name member,a.EXT_ATT1 opinion\n"
			+ "from CTP_COMMENT_ALL a left join ORG_MEMBER m on a.CREATE_ID = m.id \n"
			+ "left join ORG_POST p on m.ORG_POST_ID = p.id\n"
			+ "where a.MODULE_ID=? and a.EXT_ATT1 = 'collaboration.dealAttitude.termination' and rownum =1";

	private static final String QUERYMESSAGE_CANCEL_SQL = "select p.NAME||'/'||m.name member from ORG_MEMBER m left join ORG_POST p on m.ORG_POST_ID = p.id where m.id =?";

	private static final String QUERYMESSAGE_STEPBACK_SQL = "select to_char(a.CONTENT) msg,p.NAME||'/'||m.name member,a.EXT_ATT1 opinion\n"
			+ "from CTP_COMMENT_ALL a left join ORG_MEMBER m on a.CREATE_ID = m.id \n"
			+ "left join ORG_POST p on m.ORG_POST_ID = p.id\n"
			+ "where a.MODULE_ID=? and a.EXT_ATT1 = 'collaboration.dealAttitude.rollback' and rownum =1";;

	private static final String XMLTEMPLATE = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cus=\"http://siebel.com/CustomUI\"><soapenv:Header>\n"
			+ "<wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/07/secext\">\n"
			+ "<wsse:UsernameToken xmlns:wsu=\"http://schemas.xmlsoap.org/ws/2002/07/utility\">\n"
			+ "<wsse:Username>GUESTERM</wsse:Username>\n"
			+ "<wsse:Password Type=\"wsse:PasswordText\">GUESTERM</wsse:Password>\n" + "</wsse:UsernameToken>\n"
			+ "</wsse:Security>\n" + "</soapenv:Header>\n" + "   <soapenv:Body>\n"
			+ "      <cus:FYOAApproveServiceAccntApprove_Input>\n"
			+ "         <cus:Accountfinalstatus></cus:Accountfinalstatus>\n"
			+ "         <cus:AccounId></cus:AccounId>\n" + "			<cus:Accountmessage></cus:Accountmessage>\n"
			+ "         <cus:Accountposition></cus:Accountposition>\n"
			+ "         <cus:Oacreateddatetime></cus:Oacreateddatetime>\n"
			+ "      </cus:FYOAApproveServiceAccntApprove_Input>\n" + "   </soapenv:Body>\n" + "</soapenv:Envelope>";

	class NewCustomer {
		@Override
		public String toString() {
			return "NewCustomer [accountfinalstatus=" + accountfinalstatus + ", accounId=" + accounId
					+ ", accountmessage=" + accountmessage + ", accountposition=" + accountposition
					+ ", aacreateddatetime=" + aacreateddatetime + "]";
		}

		private String accountfinalstatus;
		private String accounId;
		private String accountmessage;
		private String accountposition;
		private String aacreateddatetime;

		public String getAccountfinalstatus() {
			return accountfinalstatus;
		}

		public void setAccountfinalstatus(String accountfinalstatus) {
			this.accountfinalstatus = accountfinalstatus;
		}

		public String getAccounId() {
			return accounId;
		}

		public void setAccounId(String accounId) {
			this.accounId = accounId;
		}

		public String getAccountmessage() {
			return accountmessage;
		}

		public void setAccountmessage(String accountmessage) {
			this.accountmessage = accountmessage;
		}

		public String getAccountposition() {
			return accountposition;
		}

		public void setAccountposition(String accountposition) {
			this.accountposition = accountposition;
		}

		public String getAacreateddatetime() {
			return aacreateddatetime;
		}

		public void setAacreateddatetime(String aacreateddatetime) {
			this.aacreateddatetime = aacreateddatetime;
		}
	}
}
